package com.talkyun.utils;

import java.util.ArrayList;
import java.util.List;

public class LooperPool {
    public interface LooperBuilder {
        Looper build();
    }

    private int threadNum;
    private LooperBuilder builder;
    private List<Looper> looperList = new ArrayList<Looper>();

    public LooperPool(int threadNum, LooperBuilder builder) {
        this.threadNum = threadNum;
        this.builder = builder;
    }

    public void startup() {
        for (int i = 0; i < threadNum; i++) {
            Looper looper = builder.build();
            looperList.add(looper);
            Thread t = new Thread(looper, looper.getName());
            t.setDaemon(true);
            t.start();
        }
    }

    public void shutdown() {
        for (Looper looper : looperList) {
            looper.shutdown();
        }
    }


    public static void main(String[] args) {
        LooperPool pool = new LooperPool(2, new LooperBuilder() {
            @Override
            public Looper build() {
                return new Looper("hello", 1000) {
                    @Override
                    protected void loop() {
                        System.out.println(System.currentTimeMillis() + " -->");
                    }
                };
            }
        });

        pool.startup();
        pool.shutdown();
    }

}